<template>
    <div class="common-layout">
        <el-container>
            <el-header style="text-align: right; font-size: 12px">
                <el-dropdown>
                    <el-icon style="margin-right: 8px; margin-top: 1px">
                        <Setting />
                    </el-icon>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item
                                v-for="item in headerList"
                                :key="item"
                                @click="headerJump(item)"
                            >
                                {{ item.name }}
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <span
                    ><el-icon><Location /></el-icon>当前位置:
                    {{ currentPage }}</span
                >
                <span>{{ userStore.getUser().name }}</span>
            </el-header>

            <el-container class="main-container">
                <el-aside
                    :width="isCollapse ? '80px' : '200px'"
                    class="aside"
                    @click="toggleAside"
                    @mouseleave="collapseAside"
                >
                    <el-menu
                        v-model="activeIndex"
                        class="el-menu-vertical-demo"
                        :collapse="isCollapse"
                    >
                        <el-sub-menu
                            v-for="item in filteredAsideList"
                            :key="item.index"
                            :index="item.index"
                        >
                            <template #title>
                                <el-icon><component :is="item.icon" /></el-icon>
                                <span>{{ item.partName }}</span>
                            </template>

                            <el-menu-item-group>
                                <el-menu-item
                                    v-for="sub in item.children"
                                    :key="sub.index"
                                    :index="sub.index"
                                    @click="asideJump(sub)"
                                >
                                    {{ sub.name }}
                                </el-menu-item>
                            </el-menu-item-group>
                        </el-sub-menu>
                    </el-menu>
                </el-aside>

                <el-main class="main">
                    <router-view></router-view>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script setup>
import router from "@/router";
import { ElNotification } from "element-plus";
import { createWebSocketConnection } from "@/utils/WebSocket";
// 修改websocket.js的引入方式
import SockJS from "sockjs-client/dist/sockjs.min.js"; // 使用压缩后的浏览器版本
import {
    getCurrentInstance,
    ref,
    computed,
    onMounted,
    onBeforeUnmount,
} from "vue";
const { proxy } = getCurrentInstance();

import { useUserStore } from "@/store/User";
const userStore = useUserStore();
const currentPage = ref("首页");
import {
    Location,
    MapLocation,
    Money,
    Setting,
    Stamp,
    DocumentChecked,
    Histogram,
    View,
    User,
} from "@element-plus/icons-vue";
import message from "@/utils/Message";

const isCollapse = ref(true);
const activeIndex = ref("");

const asideList = ref([
    {
        index: "1",
        type: "经理",
        partName: "审批",
        icon: Stamp,
        children: [
            {
                index: "1-1",
                name: "审批出差申请",
                path: "/manager/ApproveTravel",
            },
            {
                index: "1-2",
                name: "审批报销申请",
                path: "/manager/ApproveReimbursement",
            },
        ],
    },
    {
        index: "2",
        type: "经理",
        partName: "记录",
        icon: DocumentChecked,
        children: [
            {
                index: "2-1",
                name: "审批出差申请记录",
                path: "/manager/ApproveTravelRecord",
            },
            {
                index: "2-2",
                name: "审批报销申请记录",
                path: "/manager/ApproveReimbursementRecord",
            },
        ],
    },
    {
        index: "3",
        type: "财务人员",
        partName: "审批",
        icon: Stamp,
        children: [
            {
                index: "3-1",
                name: "审批预支款申请",
                path: "/financialStaff/ApproveAdvancePayment",
            },
            {
                index: "3-2",
                name: "审批报销申请",
                path: "/financialStaff/ApproveReimbursement",
            },
        ],
    },
    {
        index: "4",
        type: "财务人员",
        partName: "处理",
        icon: Money,
        children: [
            {
                index: "4-1",
                name: "财务人员处理预支款",
                path: "/financialStaff/HandleAdvancePayment",
            },
            {
                index: "4-2",
                name: "财务人员处理报销款",
                path: "/financialStaff/HandleReimbursement",
            },
        ],
    },
    {
        index: "5",
        type: "财务人员",
        partName: "审批记录",
        icon: DocumentChecked,
        children: [
            {
                index: "5-1",
                name: "审批预支款申请记录",
                path: "/financialStaff/ApproveAdvancePaymentRecord",
            },
            {
                index: "5-2",
                name: "审批报销申请记录",
                path: "/financialStaff/ApproveReimbursementRecord",
            },
        ],
    },
    {
        index: "6",
        type: "财务人员",
        partName: "报表",
        icon: Histogram,
        children: [
            {
                index: "6-1",
                name: "财务人员查看报表",
                path: "/report/ViewReport",
            },
        ],
    },
    {
        index: "7",
        type: "员工",
        partName: "出差",
        icon: MapLocation,
        children: [
            {
                index: "7-1",
                name: "员工申请出差行程",
                path: "/travel/TravelStandards",
            },
        ],
    },
    {
        index: "8",
        type: "员工",
        partName: "查看",
        icon: View,
        children: [
            {
                index: "8-2",
                name: "查看出差流程",
                path: "/travel/TravelProcess",
            },
        ],
    },
    {
        index: "9",
        type: "员工",
        partName: "报销",
        icon: Money,
        children: [
            {
                index: "9-1",
                name: "员工提交报销",
                path: "/Reimbursement/NeedReimbursement",
            },
        ],
    },
    {
        index: "10",
        type: "经理",
        partName: "个人信息",
        icon: User,
        children: [
            {
                index: "10-1",
                name: "修改个人信息",
                path: "/User/UpdateUserInfo",
            },
        ],
    },
    {
        index: "11",
        type: "财务人员",
        partName: "个人信息",
        icon: User,
        children: [
            {
                index: "11-1",
                name: "修改个人信息",
                path: "/User/UpdateUserInfo",
            },
        ],
    },
    {
        index: "12",
        type: "员工",
        partName: "个人信息",
        icon: User,
        children: [
            {
                index: "12-1",
                name: "修改个人信息",
                path: "/User/UpdateUserInfo",
            },
        ],
    },
]);

const filteredAsideList = computed(() => {
    const position = userStore.getUser().position;
    return asideList.value.filter((item) => item.type === position);
});

const asideJump = (data) => {
    if (data.path === undefined) {
        proxy.Message.success("该功能尚未开通");
    }

    if (data.path !== router.currentRoute.value.path) {
        currentPage.value = data.name;
        router.push(data.path);
    }
};

const headerList = ref([
    {
        name: "退出登录",
        path: "/Login",
    },
]);

const headerJump = (data) => {
    if (data.path === undefined) {
        proxy.Message.success("该功能尚未开通");
    }
    activeIndex.value = data.index;

    if (data.path !== router.currentRoute.value.path) {
        router.push(data.path);
    }
};

const toggleAside = () => {
    isCollapse.value = false;
};

const collapseAside = () => {
    isCollapse.value = true;
};

let connection1 = null; // 第一个WebSocket连接实例
let connection2 = null; // 第二个WebSocket连接实例
let connectionApproveTravelApply = null;
let connectionApproveAdvanceApply = null;
let connectionApproveReimbursementMaApply = null;
let connectionApproveReimbursementFiApply = null;

const handleNewMessage = (message) => {
    if (userStore.getUser().position === "经理") {
        console.log("message" + message.message);
        ElNotification({
            title: "新的出差申请",
            message: `员工：${message.message}`,
            type: "success",
            position: "top-right",
            duration: 5000,
            dangerouslyUseHTMLString: true,
            onClick: () => {
                // 点击通知跳转到审批页面
                router.push("/manager/ApproveTravel");
            },
        });
    }
};

const handleApproveTravelApply = (message) => {
    console.log("yyykkkmessage: " + message);
    if (
        userStore.getUser().position === "员工" &&
        userStore.getUser().userId == message.userId
    ) {
        console.log("message" + message.message);
        const notificationType = message.status === 2 ? "warning" : "success";
        ElNotification({
            title: "出差申请已审批",
            message: `${message.message}`,
            type: notificationType,
            position: "top-right",
            duration: 5000,
            dangerouslyUseHTMLString: true,
            onClick: () => {
                router.push("/travel/TravelProcess");
            },
        });
    }

    if (userStore.getUser().position === "财务人员" && message.status === 1) {
        console.log("message" + message.message);
        ElNotification({
            title: "出差申请已审批",
            message: `经理已批准员工${message.userId}的出差申请`,
            type: "success",
            position: "top-right",
            duration: 5000,
            dangerouslyUseHTMLString: true,
            onClick: () => {
                router.push("/financialStaff/ApproveAdvancePayment");
            },
        });
    }
};

const handleApproveAdvanceApply = (message) => {
    console.log("yyykkkmessage: " + message);
    if (
        userStore.getUser().position === "员工" &&
        userStore.getUser().userId == message.userId
    ) {
        console.log("message" + message.message);
        const notificationType = message.status === 2 ? "warning" : "success";
        ElNotification({
            title: "预支款申请已审批",
            message: `${message.message}`,
            type: notificationType,
            position: "top-right",
            duration: 5000,
            dangerouslyUseHTMLString: true,
            onClick: () => {
                router.push("/travel/TravelProcess");
            },
        });
    }
};

const handleApproveReimbursementMaApply = (message) => {
    console.log("yyykkkmessage: " + message);
    if (
        userStore.getUser().position === "员工" &&
        userStore.getUser().userId == message.userId
    ) {
        console.log("message" + message.message);
        const notificationType = message.status === 2 ? "warning" : "success";
        ElNotification({
            title: "报销申请已被经理审批",
            message: `${message.message}`,
            type: notificationType,
            position: "top-right",
            duration: 5000,
            dangerouslyUseHTMLString: true,
            onClick: () => {
                router.push("/travel/TravelProcess");
            },
        });
    }

    if (userStore.getUser().position === "财务人员" && message.status === 1) {
        console.log("message" + message.message);
        ElNotification({
            title: "报销申请已被经理审批",
            message: `经理已批准员工${message.userId}的报销申请`,
            type: "success",
            position: "top-right",
            duration: 5000,
            dangerouslyUseHTMLString: true,
            onClick: () => {
                router.push("/financialStaff/ApproveAdvancePayment");
            },
        });
    }
};

const handleApproveReimbursementFiApply = (message) => {
    console.log("yyykkkmessage: " + message);
    if (
        userStore.getUser().position === "员工" &&
        userStore.getUser().userId == message.userId
    ) {
        console.log("message" + message.message);
        const notificationType = message.status === 2 ? "warning" : "success";
        ElNotification({
            title: "报销申请已审批",
            message: `${message.message}`,
            type: notificationType,
            position: "top-right",
            duration: 5000,
            dangerouslyUseHTMLString: true,
            onClick: () => {
                router.push("/travel/TravelProcess");
            },
        });
    }
};

const handleNewTravelApply = (message) => {
    if(userStore.getUser().position === "经理") {
        console.log(message);
        ElNotification({
            title: "新的出差申请",
            message: message.message,
            type: "info",
            position: "top-right",
            duration: 5000,
            dangerouslyUseHTMLString: true
        })
    }

}

// 生命周期
onMounted(() => {
    // 建立第一个WebSocket连接（端口8401）
    connection1 = createWebSocketConnection("http://localhost:8401/ws", [
        { topic: "/topic/travelRequests", callback: handleNewMessage },
    ]);

    // 建立第二个WebSocket连接（端口8402）
    // connection2 = createWebSocketConnection("http://localhost:8402/ws", [
    //     { topic: "/topic/systemAlerts", callback: handleSystemAlert },
    // ]);
    connection2 = createWebSocketConnection("http://localhost:8401/ws", [
        { topic: "/topic/approvalMessage", callback: handleNewTravelApply },
    ]);


    connectionApproveTravelApply = createWebSocketConnection(
        "http://localhost:8401/ws",
        [
            {
                topic: "/topic/approveTravelApply",
                callback: handleApproveTravelApply,
            },
        ]
    );

    connectionApproveTravelApply = createWebSocketConnection(
        "http://localhost:8401/ws",
        [
            {
                topic: "/topic/approveAdvanceApply",
                callback: handleApproveAdvanceApply,
            },
        ]
    );

    connectionApproveReimbursementMaApply = createWebSocketConnection(
        "http://localhost:8401/ws",
        [
            {
                topic: "/topic/approveReimbursementMaApply",
                callback: handleApproveReimbursementMaApply,
            },
        ]
    );

    connectionApproveReimbursementFiApply = createWebSocketConnection(
        "http://localhost:8401/ws",
        [
            {
                topic: "/topic/approveReimbursementFiApply",
                callback: handleApproveReimbursementFiApply,
            },
        ]
    );
});

onBeforeUnmount(() => {
    if (connection1) connection1.disconnect(); // 断开第一个连接
    if (connection2) connection2.disconnect(); // 断开第二个连接
    if (connectionApproveTravelApply) connectionApproveTravelApply.disconnect();
    if (connectionApproveAdvanceApply) connectionApproveAdvanceApply.disconnect();
    if (connectionApproveReimbursementMaApply) connectionApproveReimbursementMaApply.disconnect();
    if (connectionApproveReimbursementFiApply) connectionApproveReimbursementFiApply.disconnect();
});
</script>

<style lang="less" scoped>
.common-layout {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    height: 100vh;
    display: flex;
    flex-direction: column;
}

.main-container {
    display: flex;
    flex: 1;
    height: 100%;
}

.aside {
    transition: width 0.3s ease;
    height: 100%;
    overflow: hidden;
}

.main {
    height: 100%;
    flex: 1;
    padding: 20px;
    overflow: auto;
}

.el-header {
    position: relative;
    background: linear-gradient(90deg, #f8f8f8, #f0f0f0);
    color: #333;
    font-size: 14px;
    padding: 10px 20px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    border-radius: 8px 8px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.el-header span {
    font-weight: bold;
    font-size: 16px;
    color: #333;
    margin-right: 20px;
}

.el-dropdown {
    display: inline-flex;
    align-items: center;
    cursor: pointer;
}

.el-icon {
    font-size: 20px;
    color: #333;
    transition: color 0.3s ease;
}

.el-icon:hover {
    color: #409eff;
}

.el-dropdown-menu {
    width: 150px;
}

.el-dropdown-item {
    font-size: 14px;
    padding: 10px;
    color: #333;
    transition: background-color 0.3s ease;
}

.el-dropdown-item:hover {
    background-color: #f0f0f0;
}
</style>
